<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */
 
class CartController extends Zenddn_Controller_Action{
	
	public function init(){
		parent::init();
        $this->loadTemplate('magashop');
	}
	
	public function indexAction(){
		$this->getCart();
	}
    
    public function checkoutAction(){
    	$request = $this->_request;
        
        $qty = $this->getCart();
        
        if($qty == 0){
            $this->_helper->_redirector->gotoRoute(array(), 'cart', true);
        }
        
        
        if($request->isPost()){
            $validator = new Default_Form_Order($request->getParam('customer'));
            
            if($validator->isError()){
                $this->view->error = $validator->getMessageError();
            }else{
                $cart = new Zend_Session_Namespace('cart');
                
                $items = $cart->items;
                $total = 0;
                $quantity = 0;
                
                foreach($items as $item){
                    $total += $item['subtotal'];
                    $quantity += $item['qty'];
                }
                
                $data = $validator->getData();
                $data['total'] = $total;
                $data['items'] = serialize($items);
                $data['status'] = false;
                
                $model = new Default_Model_Order();
                $order_id = $model->saveData($data);
                
                if($order_id){
                    $nl = new Default_Model_Nganluong();
                    
                    $url = $this->view->webinfo("url") . "/gio-hang/xac-nhan-thanh-toan.html";
                    $email = "nhatdo@outlook.com";
                    $transaction_info = "Thanh toán cho đơn hàng số $order_id tại http://dietvirut.com.";
                    $order_id = $order_id;
                    $price = $total;
                    
                    $urlCheckout = $nl->buildCheckoutUrl($url, $email, $transaction_info, $order_id, $price);
                    
                    unset($cart->items);
                    unset($cart->subtotal);
                    $this->_helper->_redirector->gotoUrl($urlCheckout);
                }
            }
        }
        
        $layout = $this->_helper->layout()->setLayout('product-detail');
    }
    
    public function confirmAction(){
        $this->_helper->layout()->setLayout('product-detail');
    	//$this->_helper->layout()->disableLayout();
        //$this->_helper->viewRenderer->setNoRender();
        
        $title = "payment unsuccess";
        $message = "payment unsuccess message";
        
        $request = $this->_request;
        $baseUrl = $this->view->baseUrl();
        
        $transaction_info = $request->getParam('transaction_info');
        $order_code = $request->getParam('order_code');
        $price = $request->getParam('price');
        $payment_id = $request->getParam('payment_id');
        $payment_type = $request->getParam('payment_type');
        $error_text = $request->getParam('error_text');
        $secure_code = $request->getParam('secure_code');
        
        $nl = new Default_Model_Nganluong();
        
        $check = $nl->verifyPaymentUrl($transaction_info, $order_code, $price, $payment_id, $payment_type, $error_text, $secure_code);
        
        if($check){
            $order_model = new Default_Model_Order();
            $order = $order_model->getData($order_code, null, false);
            
            if($order != null){
	            $items = unserialize($order['items']);
	            
	            $key_model = new Default_Model_ProductKey();
	            $product_model = new Default_Model_Product();
	            
	            $keys = array();
	            
	            foreach($items as $item){
	                for($i = 1; $i <= $item['qty']; $i ++){
	                    $key = $key_model->getData($item['id']);
	                    
	                    if($key){
	                        $keys[] = $key;
	                        $key_model->updateStatus($key->id);
	                        $key_model->saveOrderKeys($key->id, $order_code);
	                        $product_model->updateQuantity($item['id']);
	                    }
	                }
	            }
	            
	            $this->view->name = $order['name'];
	            $this->view->items = $keys;
	            $content = $this->view->render("email/key.phtml");
	            
	            $mail = new Zenddn_Mail_Mail();
	            $mail->sendProductKey($order['email'], $order['name'], $content);
	            
	            $date = new Zend_Date();
	            $curDate = $date->get(Zend_Registry::get('date_format_insert'));
	            
	            $data['id'] = $order_code;
	            $data['status'] = true;
	            $data['purchase_date'] = $curDate;
	            
	            $order_model->saveData($data);
	            
	            $title = "payment success";
	            $message = "payment success message";
            }
        }
        
        $this->view->title = $title;
        $this->view->message = $message;
    }
    
    public function successAction(){
    	
    }
    
    public function addAction(){
        $request = $this->_request;
        
        if($request->isXmlHttpRequest()){
            $id = $request->getParam('id', false);
            $qty = $request->getParam('qty', 0);
            $price = $request->getParam('price', 0);
            
            if($id == true && $qty > 0 && $price > 0){
                $cart = new Zend_Session_Namespace('cart');
                
                $items = array();
                $subtotal = 0;
                $cart->subtotal = $subtotal;
                
                if(isset($cart->items)){
                    $items = $cart->items;
                    
                    foreach($cart->items as $item){
                        $subtotal += $item['subtotal'];
                    }
                }
                
                $items[$id]['id'] = $id;
                $items[$id]['qty'] = $qty;
                $items[$id]['price'] = $price;
                $items[$id]['subtotal'] = $price * $qty;
                
                $cart->items = $items;
                $cart->subtotal = $subtotal + $items[$id]['subtotal'];
            }
        }
        
        $this->_helper->layout->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    }
    
    public function viewAction(){
    	$request = $this->_request;
        
        if($request->isXmlHttpRequest()){
            $cart = new Zend_Session_Namespace('cart');
            
            $qty = 0;
            
            if(isset($cart->items)){
                $items = $cart->items;
                $subtotal = 0;
                $qty = count($items);
                
                $model = new Default_Model_Product();
                
                foreach($items as $id => $item){
                    $p = $model->getData($item['id']);
                    
                    $items[$id]['name'] = $p['name'];
                    $items[$id]['image'] = $p['image'];
                    
                    $price = $items[$id]['price'] * $items[$id]['qty'];
                    
                    $items[$id]['subtotal'] = $price;
                    $subtotal += $price;
                }
                
                $this->view->items = $items;
                $this->view->subtotal = $subtotal;
            }
            
            $this->view->qty = $qty;
        }
        
        $this->_helper->layout->disableLayout();
    }
    
    public function deleteAction(){
    	$request = $this->_request;
        
        if($request->isXmlHttpRequest()){
            $id = $request->getParam('id', false);
            
            if($id){
                $cart = new Zend_Session_Namespace('cart');
                
                $items = array();
                $subtotal = 0;
                $cart->subtotal = $subtotal;
                
                if(isset($cart->items)){
                    $items = $cart->items;
                    
                    foreach($items as $itemId => $item){
                        if($itemId == $id){
                            unset($items[$id]);
                        }else{
                            $subtotal += $item['subtotal'];
                        }
                    }
                }
                                
                $cart->items = $items;
                $cart->subtotal = $subtotal;
            }
        }
        
        $this->_helper->layout->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    }
    
    private function getCart(){
        $cart = new Zend_Session_Namespace('cart');
            
        $qty = 0;
        
        if(isset($cart->items)){
            $items = $cart->items;
            $subtotal = 0;
            $qty = count($items);
            
            $model = new Default_Model_Product();
            
            foreach($items as $id => $item){
                $p = $model->getData($item['id']);
                
                $items[$id]['name'] = $p['name'];
                $items[$id]['image'] = $p['image'];
                
                $price = $items[$id]['price'] * $items[$id]['qty'];
                
                $items[$id]['subtotal'] = $price;
                $subtotal += $price;
            }
            
            $this->view->items = $items;
            $this->view->subtotal = $subtotal;
        }
        
        $this->view->qty = $qty;
        
        return $qty;
    }
}